import { defineAppConfig, history, defineDataLoader } from 'ice';
import { fetchUserInfo } from './services/user';
import { defineAuthConfig } from '@ice/plugin-auth/types';
import { defineStoreConfig } from '@ice/plugin-store/types';
import { defineRequestConfig } from '@ice/plugin-request/types';
import { ROLE } from '@/common/const'

export default defineAppConfig(() => ({
  router: {
    type: 'hash'
  }
}));

export const authConfig = defineAuthConfig(async (appData) => {
  const { userInfo = {} } = appData;
  if (userInfo.error) {
    history?.push(`/login`);
  }
  return {
    initialAuth: {
      ADMIN: (userInfo.role as string).toUpperCase() === ROLE.ADMIN,
      ZL: userInfo.role === ROLE.ZL,
      YS: userInfo.role === ROLE.YS,
      CKY: userInfo.role === ROLE.CKY,
      RKY: userInfo.role === ROLE.RKY,
      HS: userInfo.role === ROLE.HS,
      YK: userInfo.role === ROLE.YK,
    },
  };
});

export const storeConfig = defineStoreConfig(async (appData) => {
  const { userInfo = {} } = appData;
  return {
    initialStates: {
      user: {
        currentUser: userInfo,
      },
    },
  };
});

export const requestConfig = defineRequestConfig(() => {
  return {
    baseURL: location.hash.includes('mock=') ? 'http://127.0.0.1:3000/api' : `${process.env.ICE_APP_HOST}/api`
  }
});

export const dataLoader = defineDataLoader(async () => {
  if (location.hash.includes('/login') || location.hash === '' || location.hash === '#/') {
    return {
      userInfo: { role: '游客' }
    }
  }
  const userInfo = await getUserInfo();
  // 这里定义appData中的数据，会率先执行
  return {
    userInfo,
  };
});

async function getUserInfo() {
  try {
    const { data, code } = await fetchUserInfo();
    if (code === 200) {
      return data;
    } else {
      return {
        error: '获取用户信息失败'
      }
    }
  } catch (error) {
    return {
      error,
    };
  }
}
